import { createSlice } from '@reduxjs/toolkit';

// 创建图像编辑slice
const imageEditSlice = createSlice({
  name: 'imageEdit',
  initialState: {
    uploadedImages: {}, // 存储上传的图片 {menuKey_uploadKey: imageUrl}
    currentImage: null,   // 当前显示的单张图片
    currentVideo: null,   // 当前显示的视频
    layerImages: []      // layer模式下的图片列表
  },
  reducers: {
    setUploadedImage: (state, action) => {
      const { key, imageUrl } = action.payload;
      state.uploadedImages[key] = imageUrl;
      // 如果是单张图片上传，同时更新currentImage
      
      if (key.includes('single') || key.includes('main') || key.includes('uploadImg')) {
        state.currentImage = imageUrl;
      }
    },
    setCurrentImage: (state, action) => {
      state.currentImage = action.payload;
    },
    setCurrentVideo: (state, action) => {
      state.currentVideo = action.payload;
    },
    clearImages: (state) => {
      state.uploadedImages = {};
      state.currentImage = null;
      state.layerImages = [];
    },
    removeImage: (state, action) => {
      const key = action.payload;
      delete state.uploadedImages[key];
      if (state.currentImage === state.uploadedImages[key]) {
        state.currentImage = null;
      }
    },
    updateCurrentImageByMenuKey: (state, action) => {
      const { menuKey, imageUrl } = typeof action.payload === 'string' 
        ? { menuKey: action.payload, imageUrl: null } 
        : action.payload;
      
      // 如果直接传入了imageUrl，直接设置为当前图片
      if (imageUrl) {
        state.currentImage = imageUrl;
        return;
      }
      
      // 根据menuKey查找对应的图片
      const imageKey = Object.keys(state.uploadedImages).find(key => 
        key.startsWith(menuKey) || key.includes(menuKey)
      );
      if (imageKey && state.uploadedImages[imageKey]) {
        state.currentImage = state.uploadedImages[imageKey];
      } else {
        // 如果没有找到对应的图片，清空当前图片
        state.currentImage = null;
      }
    },
    addLayerImage: (state, action) => {
      const { imageUrl, frameType } = typeof action.payload === 'string' 
        ? { imageUrl: action.payload, frameType: null }
        : action.payload;
      
      if (imageUrl && !state.layerImages.some(img => img.src === imageUrl)) {
        const now = new Date();
        let fileName;
        
        if (frameType === 'first') {
          fileName = '首帧';
        } else if (frameType === 'last') {
          fileName = '尾帧';
        } else {
          fileName = now.getHours().toString().padStart(2, '0') + 
                    now.getMinutes().toString().padStart(2, '0') + 
                    now.getSeconds().toString().padStart(2, '0');
        }
        
        state.layerImages.push({ 
          src: imageUrl, 
          fileName,
          id: Date.now(),
          frameType: frameType || null
        });
      }
    },
    removeLayerImage: (state, action) => {
      const imageUrl = action.payload;
      state.layerImages = state.layerImages.filter(img => img.src !== imageUrl);
    },
    clearLayerImages: (state) => {
      state.layerImages = [];
    },
    clearLayerVideo: (state) => {
      state.currentVideo = null;
    },
    reorderLayerImages: (state, action) => {
      const { fromIndex, toIndex } = action.payload;
      const images = [...state.layerImages];
      const [movedImage] = images.splice(fromIndex, 1);
      images.splice(toIndex, 0, movedImage);
      state.layerImages = images;
    }
  }
});

// 导出actions
export const { setUploadedImage, setCurrentImage, setCurrentVideo, clearImages, removeImage, updateCurrentImageByMenuKey, addLayerImage, removeLayerImage, clearLayerImages,clearLayerVideo, reorderLayerImages } = imageEditSlice.actions;

// 导出reducer
export default imageEditSlice.reducer;

// 导出选择器
export const selectImageEdit = (state) => state.imageEdit;
export const selectCurrentImage = (state) => state.imageEdit.currentImage;
export const selectCurrentVideo = (state) => state.imageEdit.currentVideo;
export const selectUploadedImages = (state) => state.imageEdit.uploadedImages;
export const selectLayerImages = (state) => state.imageEdit.layerImages;